#include "bsp_eeprom.h"
#include "intrins.h"



uint8_t eeprom_read_1byte(uint8_t addr){
	unsigned char tmp_dat;
	
	EECON  = (1 << DLYS1)|(1 << DLYS0);
	
	EEADRL = addr;
	EEADRH = 0;
	EECON |= (1 << READ_EE );//enable read eeprom byte
	_nop_();
	tmp_dat = EEDATA;
	return tmp_dat;
}



void eeprom_write_1byte(uint8_t addr, uint8_t dat){
	EECON  = (1 << DLYS1)|(1 << DLYS0);
	
	EEADRL = addr;
	EEADRH = 0;
	EECON |= (1 << ERASE_EE );//set byte erase
	while ((EECON & (1 << ERASE_EE)) != 0x00);//wait for all byte erase complete
	
	EEDATA = dat;
	EECON |= (1 << PROG_EE );//write eeprom byte
	while ((EECON & (1 << PROG_EE)) != 0x00);//wait for write eeprom byte complete
}


void ReadEeprom_4Byte(uint8_t EE_Addar, uint8_t *dat)
{
    *dat++ = eeprom_read_1byte(EE_Addar++);
    *dat++ = eeprom_read_1byte(EE_Addar++);
    *dat++ = eeprom_read_1byte(EE_Addar++);
    *dat = eeprom_read_1byte(EE_Addar);
    
}

void ee_read_buf(unsigned char EEPROM_Addr, unsigned char *buf, unsigned char len)
{
	while (len--)
	{
		*buf++ = eeprom_read_1byte(EEPROM_Addr++);
	}
}

void Earse_Eeprom_1Byte(uint8_t EE_Addar)
{
	EECON  = (1 << DLYS1)|(1 << DLYS0);
	
	EEADRL = EE_Addar;
	EEADRH = 0;
	EECON |= (1 << ERASE_EE );//set byte erase
	while ((EECON & (1 << ERASE_EE)) != 0x00);//wait for all byte erase complete
}




void write_2byte(u8 addr, u16 dat)
{
	eeprom_write_1byte(addr+0, dat>>8);
	eeprom_write_1byte(addr+1, dat&0xFF);
}

u16 read_2byte(u8 addr)
{
	u16 dat;
	dat = eeprom_read_1byte(addr+0);
	dat <<= 8;
	dat |= eeprom_read_1byte(addr+1);
	return dat;
}


